<template>
    <h1>轮播图列表</h1>
    <el-table :data="bannerList" style="width: 100%">
        <el-table-column prop="bannerid" label="轮播图编号" width="180" />
        <el-table-column label="图片" width="180">
            <template #default="scope">
                <img class="img" :src="scope.row.img" />
            </template>
        </el-table-column>
        <el-table-column prop="alt" label="图片提示" width="180" />
        <el-table-column prop="link" label="图片连接" width="180" />
        <el-table-column label="是否启用">
            <template #default="scope">
                <el-switch v-model="scope.row.flag" @change="(val: boolean) => updateBannerFlag(scope.row.bannerid, val)" />
            </template>
        </el-table-column>
        <el-table-column label="操作">
            <template #default="scope">
                <el-popconfirm title="亲，您真的要删除吗?" @confirm="deleteBannner(scope.row.bannerid)">
                    <template #reference>
                        <el-button>删除</el-button>
                    </template>
                </el-popconfirm>
            </template>


        </el-table-column>
    </el-table>
</template>
  
<script setup lang="ts">

import { ElMessage } from 'element-plus';
import 'element-plus/dist/index.css';

import { reactive } from "vue";
import service from "../../../utils/service";




interface IBanner {
    link: string,
    img: string,
    alt: string,
    bannerid: string,
    flag: boolean
}

// 1、定义轮播图数据
let bannerList = reactive<IBanner[]>([]);
// 2、获取所有的轮播图数据
const getBannerList = () => {
    service({
        url: "/banner/list"
    })
        .then((res: any) => {
            if (res.data.code === "200") {
                // bannerList = res.data.data;
                bannerList.length = 0;
                bannerList.push(...res.data.data);
            }
        })
}

// 3、更新轮播图的访问状态
const updateBannerFlag = (bannerid: string, val: boolean) => {
    service({
        url: "/banner/updateFlag",
        method: 'post',
        data: {
            bannerid: bannerid,
            flag: val
        }
    }).then(res => {
        if (res.data.code === "200") {
            alert("更新成功");
        }
    })
}

getBannerList();


// 4、删除轮播图
const deleteBannner = (bannerid: string) => {

    service({
        url: "/banner/delete",
        params: {
            bannerid
        }
    })
        .then(res => {
            if (res.data.code === "200") {
                // alert("删除成功！");
                ElMessage({
                    message: '删除成功！',
                    type: 'success',
                })
                // 删除成功后，两种做法：
                // 1、重新发送请求获取最新数据：缺点是多发了一次请求。
                // getBannerList();
                // 2、删除前端的数组。缺点：如果多人同时操作数据，那么，就看不到别人删除的数据。
                let index = bannerList.findIndex(item => item.bannerid === bannerid);
                bannerList.splice(index, 1);
            }
        })

}
</script>
  
<style scoped>
.img {
    width: 200px;
    height: 150px;
}
</style>